package com.jiao.config;

import com.jiao.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    /*
    * 导入密码加密组件
    * */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        //关闭csrf
        .csrf().disable()
        //不通过Session获取SecurityContext
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        // 对于登录接口 允许匿名访问
        .antMatchers("/Blog/login").anonymous()
        //注销接口需要认证才能访问
        .antMatchers("/Blog/logout").authenticated()
        //个人信息接口必须登录后才能访问
        .antMatchers("/user/userInfo").authenticated()
        //发布评论接口必须登录后才能访问
        .antMatchers("/comment/insertCommentt").authenticated()
        //点赞文章接口必须登录后才能访问
        .antMatchers("/article/like").authenticated()
        //关注接口必须登录后才能访问
        .antMatchers("/user/follow").authenticated()
        // 除上面外的所有请求全部不需要认证即可访问
        .anyRequest().permitAll();


        http.logout().disable();
        //允许跨域
        http.cors();
        //把jwtAuthenticationTokenFilter添加到UsernamePasswordAuthenticationFilter过滤器的后面
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //注入自定义异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint);
    }
    /*
    * 导入AuthenticationManager组件
    * */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}